<template>
  <v-card class="Calendars-Container" :class="[zoomStatus]" flat>
    <v-row no-gutters class="header">
      <v-col class="d-flex" :cols="8">
        <v-menu ref="menu" :close-on-content-click="false" min-width="auto">
          <template v-slot:activator="{ on, attrs }">
            <div v-bind="attrs" v-on="on">
              <v-text-field
                @focus="focusMonthInput"
                ref="month-input"
                class="gray-input rounded-pill mr-2"
                dense
                hide-details
                solo
                multiple
                :value="monthText"
                append-icon="mdi-menu-down"
              >
              </v-text-field>
            </div>
          </template>
          <v-date-picker v-model="selectedMonth" type="month"></v-date-picker>
        </v-menu>
        <SelectAll
          class="gray-input rounded-pill mr-2"
          hide-details
          solo
          multiple
          scarecrow="Project"
          :items="projectList"
          :selectedItem.sync="selectedProject"
        >
        </SelectAll>
        <SelectAll
          class="gray-input rounded-pill mr-2"
          :show-search="true"
          hide-details
          solo
          multiple
          scarecrow="User"
          :items="userList"
          :selectedItem.sync="selectedUser"
        >
        </SelectAll>
        <SelectAll
          class="gray-input rounded-pill mr-2"
          hide-details
          solo
          multiple
          scarecrow="Status"
          :items="statusList"
          :selectedItem.sync="selectedStatus"
        >
        </SelectAll>
      </v-col>
      <v-col :cols="4" class="d-flex justify-end action">
        <MenuList :items="actionList" v-if="zoomStatus === 'out'">
          <template #default="{ on }">
            <v-icon class="icon mr-4" v-on="on">mdi-dots-vertical</v-icon>
          </template>
        </MenuList>
        <div v-else>
          <v-icon class="mr-4 icon">mdi-plus-thick</v-icon>
          <v-icon @click="openDispatchDialog" class="mr-4 icon">
            mdi-clipboard-text
          </v-icon>
          <v-icon @click="openExportDialog" class="mr-4 icon">
            mdi-file-send
          </v-icon>
        </div>
        <v-icon class="mr-2 icon" @click="zoomCalendar"> {{ zoomIcon }}</v-icon>
      </v-col>
    </v-row>
    <div class="type-buttons d-flex justify-end py-0 my-2 mr-3">
      <v-btn
        v-for="type in calendarsTypes"
        :key="type.value"
        :class="{ active: calendarsType === type.value }"
        @click="switchType(type.value)"
        class="rounded-pill"
        elevation="0"
        x-small
        >{{ type.text }}</v-btn
      >
    </div>
    <div class="calendar-wrap">
      <v-skeleton-loader
        v-if="loading"
        type="date-picker-days"
      ></v-skeleton-loader>
      <v-calendar
        v-else
        event-color="#DFE1E8"
        class="calendar"
        ref="calendar"
        event-end="endDate"
        event-start="startDate"
        event-name="number"
        @click:event="showEvent"
        :start="new Date(selectedMonth)"
        :event-height="16"
        :events="events"
        :weekdays="weekdays"
        :type="calendarsType"
        :weekday-format="weekdayFormatter"
      >
        <template #event="{ event, start }">
          <div v-if="start">{{ event.projectType }} - {{ event.number }}</div>
        </template>
        <template #day-label="{ day, weekday }">
          <v-btn
            class="weekday-btn"
            fab
            elevation="0"
            :class="{ 'weekday-blue': weekday === 6 || weekday === 0 }"
          >
            {{ day }}
          </v-btn>
        </template>
      </v-calendar>
      <v-menu
        v-if="selectedEvent"
        v-model="selectedOpen"
        :position-y="menuY"
        :position-x="menuX"
        :close-on-content-click="false"
        min-width="auto"
        content-class="elevation-0 event-menu"
        offset-y
        :allow-overflow="true"
        nudge-bottom="4"
      >
        <div class="arrow-wrap"></div>
        <v-card flat class="event-card" color="#616B83" width="400">
          <i
            class="arrow-up"
            :class="{ precipice: selectedEventWeekday === 0 }"
          ></i>
          <v-list-item>
            <v-list-item-avatar>
              <v-img
                height="40"
                width="40"
                :src="selectedEvent.avatar"
                alt="avatar"
              />
              <span class="user-name">
                {{ selectedEvent.principal }}
              </span>
            </v-list-item-avatar>
            <v-list-item-content class="ml-6">
              <v-list-item-title
                >{{ selectedEvent.projectType }} -
                {{ selectedEvent.number }}</v-list-item-title
              >
              <v-list-item-subtitle>{{
                selectedEvent.customerName
              }}</v-list-item-subtitle>
              <v-list-item-subtitle>{{
                selectedEvent.projectDescription
              }}</v-list-item-subtitle>
              <v-list-item-subtitle>{{
                selectedEvent.address
              }}</v-list-item-subtitle>
              <v-list-item-subtitle
                >{{ selectedEvent.startDate }} -
                {{ selectedEvent.endDate }}</v-list-item-subtitle
              >
            </v-list-item-content>
          </v-list-item>
        </v-card>
      </v-menu>
    </div>
    <ExportJobDialog
      v-model="showExport"
      @submit="exportJob"
      width="480"
      title="Export job"
    ></ExportJobDialog>
    <DispatchJobDialog
      v-model="showDispatch"
      @submit="dispatchJob"
      width="480"
      title="Dispatch Job"
    >
    </DispatchJobDialog>
  </v-card>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { CalendarTimestamp, CalendarDaySlotScope } from "vuetify/types/index";
import SelectAll from "@/components/Dashboard/SelectAll/SelectAll.vue";
import TreeSelect from "@/components/Dashboard/SelectAll/TreeSelect.vue";
import ExportJobDialog from "./ExportJobDialog.vue";
import DispatchJobDialog from "./DispatchJobDialog.vue";
import MenuList from "@/components/Menu/MenuList.vue";

interface ISelectItem {
  id: string;
  text: string;
  children?: Array<ISelectItem>;
}

interface ITaskItem {
  id: string;
  avatar: string;
  principal: string;
  customerName: string;
  projectType: string;
  number: string;
  projectDescription: string;
  address: string;
  startDate: string;
  endDate: string;
  progress: string;
  priority: string;
  status: string;
}

@Component({
  components: {
    SelectAll,
    TreeSelect,
    ExportJobDialog,
    DispatchJobDialog,
    MenuList,
  },
})
export default class Calendars extends Vue {
  get zoomStatus() {
    return this.$store.state.DashboardStore.zoomStatus;
  }

  actionList = [
    {
      icon: "mdi-plus-thick",
      text: "Add New Job",
      clickHandle: function () {
        console.log("open Add New Job");
      },
    },
    {
      icon: "mdi-clipboard-text",
      text: "Dispatch Job",
      clickHandle: this.openDispatchDialog,
    },
    {
      icon: "mdi-file-export",
      text: "Export",
      clickHandle: this.openExportDialog,
    },
  ];
  // Export Job
  showExport = false;
  openExportDialog() {
    this.showExport = true;
  }
  closeExportDialog() {
    this.showExport = false;
  }
  exportJob() {
    this.closeExportDialog();
    this.SweetAlertService.success("successfully");
  }
  // Dispatch Job
  showDispatch = false;
  openDispatchDialog() {
    this.showDispatch = true;
  }
  closeDispatchDialog() {
    this.showDispatch = false;
  }
  dispatchJob() {
    this.closeDispatchDialog();
    this.SweetAlertService.success("successfully");
  }
  // select
  selectedMonth = "2022-11";
  month: Record<string, string> = {
    Jan: "January",
    Feb: "February",
    Mar: "March",
    Apr: "April",
    May: "May",
    Jun: "June",
    Jul: "July",
    Aug: "August",
    Sept: "September",
    Oct: "October",
    Nov: "November",
    Dec: "December",
  };
  projectList: Array<ISelectItem> = [
    {
      id: "1",
      text: "Project",
    },
    {
      id: "2",
      text: "Adhoc",
    },
    {
      id: "3",
      text: "Customer Contract",
    },
  ];
  selectedProject = [this.projectList[1]];
  statusList: Array<ISelectItem> = [
    {
      id: "1",
      text: "New Job",
    },
    {
      id: "2",
      text: "Ongoing",
    },
  ];
  selectedStatus = [this.statusList[1]];
  userList: Array<ISelectItem> = [];
  selectedUser = [];
  getUserList() {
    this.userList = [
      {
        id: "1",
        text: "Admin",
        children: [
          {
            id: "2",
            text: "Angela Lo",
          },
          {
            id: "3",
            text: "Ken Wong",
          },
          {
            id: "4",
            text: "Kin Fei To",
          },
        ],
      },
      {
        id: "2",
        text: "Customer Service Team",
      },
      {
        id: "3",
        text: "Field Service Engineer",
      },
    ];
  }

  get monthText() {
    const date = new Date(this.selectedMonth);
    const shortMonth = date.toDateString().split(" ")[1];
    const fullYear = date.getFullYear();
    return `${this.month[shortMonth]} ${fullYear}`;
  }

  focusMonthInput() {
    const monthInputRef = this.$refs["month-input"] as Vue;
    (monthInputRef.$refs.input as HTMLInputElement).blur();
  }

  // headerAction
  get zoomIcon() {
    switch (this.zoomStatus) {
      case "out":
        return "mdi-arrow-expand";
      case "in":
        return "mdi-arrow-expand-all";
      case "fullscreen":
        return "mdi-arrow-collapse";
      default:
        return "";
    }
  }
  zoomCalendar() {
    switch (this.zoomIcon) {
      case "mdi-arrow-expand":
        this.switchToZoomIn();
        break;
      case "mdi-arrow-expand-all":
        this.switchToFullscreen();
        break;
      case "mdi-arrow-collapse":
        this.switchToZoomOut();
        break;
    }
  }
  // 切换到缩小状态
  switchToZoomOut() {
    this.$store.commit("DashboardStore/switchToZoomOut");
  }
  // 切换到放大状态
  switchToZoomIn() {
    this.$store.commit("DashboardStore/switchToZoomIn");
  }
  // 切换到全屏状态
  switchToFullscreen() {
    this.$store.commit("DashboardStore/switchToFullscreen");
  }

  // button group
  calendarsTypes = [
    {
      text: "Month",
      value: "month",
    },
    {
      text: "Day",
      value: "day",
    },
    {
      text: "Week",
      value: "week",
    },
  ];
  calendarsType = "month";
  switchType(type: string) {
    this.calendarsType = type;
  }

  // calendars
  weekdays = [1, 2, 3, 4, 5, 6, 0];
  events: Array<ITaskItem> | null = null;
  loading = true;
  menuY = 0;
  menuX = 0;
  getEvents() {
    this.events = [
      {
        id: "1",
        avatar:
          "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0801%2F9ceecfb8j00rfxf1200dac000kk00epm.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
        principal: "Ken Wong",
        customerName: "Auto Company",
        projectType: "DL",
        number: "2021120901.03",
        projectDescription: "Check System",
        address: "@ Cable TV Tower, 9 Hoi Shing Road, Tsuen Wan",
        startDate: "2022-11-6 15:40",
        endDate: "2022-11-7 19:40",
        progress: "60",
        priority: "High",
        status: "Ongoing",
      },
      {
        id: "2",
        avatar:
          "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0801%2F9ceecfb8j00rfxf1200dac000kk00epm.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
        principal: "Ken Wong",
        customerName: "Auto Company",
        projectType: "DL",
        number: "2021120902",
        projectDescription: "Check System",
        address: "@ Cable TV Tower, 9 Hoi Shing Road, Tsuen Wan",
        startDate: "2022-11-10 15:40",
        endDate: "2022-11-18 19:40",
        progress: "60",
        priority: "High",
        status: "Ongoing",
      },
      {
        id: "3",
        avatar:
          "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0801%2F9ceecfb8j00rfxf1200dac000kk00epm.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
        principal: "Ken Wong",
        customerName: "Auto Company",
        projectType: "DL",
        number: "2021120902",
        projectDescription: "Check System",
        address: "@ Cable TV Tower, 9 Hoi Shing Road, Tsuen Wan",
        startDate: "2022-11-19 15:40",
        endDate: "2022-11-19 19:40",
        progress: "60",
        priority: "High",
        status: "Ongoing",
      },
    ];
    // this.processEvents();
    setTimeout(() => {
      this.loading = false;
    }, 0);
  }
  weekdayFormatter(timestamp: CalendarTimestamp) {
    switch (timestamp.weekday) {
      case 1:
        return "Mo";
      case 2:
        return "Tu";
      case 3:
        return "We";
      case 4:
        return "Th";
      case 5:
        return "Fr";
      case 6:
        return "Sa";
      case 0:
        return "Su";
    }
  }
  selectedEvent: ITaskItem | null = null;
  selectedEventWeekday: null | number = null;
  selectedElement: EventTarget | null = null;
  selectedOpen = false;
  showEvent({
    day,
    nativeEvent,
    event,
  }: {
    day: CalendarDaySlotScope;
    nativeEvent: MouseEvent;
    event: ITaskItem;
  }) {
    console.log(arguments);
    const open = () => {
      this.selectedEvent = event;
      this.selectedElement = nativeEvent.target;
      this.selectedEventWeekday = day.weekday;
      this.menuX = nativeEvent.clientX;
      this.menuY = nativeEvent.clientY + 8;
      if (day.weekday === 0) {
        this.menuX -= 144;
      }
      requestAnimationFrame(() =>
        requestAnimationFrame(() => (this.selectedOpen = true))
      );
    };

    if (this.selectedOpen) {
      this.selectedOpen = false;
      requestAnimationFrame(() => requestAnimationFrame(() => open()));
    } else {
      open();
    }

    nativeEvent.stopPropagation();
  }

  created() {
    this.getEvents();
    this.getUserList();
  }
}
</script>
<style lang="scss" scoped>
@import "./Calendars.scss";
</style>
